<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;

class Back extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    // 当前模型
    protected $model = null;

    // 无需登陆
    protected $noNeedLogin = [];
    // 无需鉴权
    protected $noNeedRight = [];

    public function __construct(){
        parent::__construct();

        $this->model = model('Depot.Back');
        $this->BackProductModel = model('Depot.Productback');
        $this->OrderModel = model('Product.order.Order');
        $this->OrderProductModel = model('Product.order.Product');
        $this->AddressModel = model('Business.Address');
        $this->BusinessModel = model('Business.User');
        $this->StorageModel = model('Depot.Storage');
        $this->StorageProductModel = model('Depot.Productstorage');

        $statusList = [
            0 => '未审核',
            1 => '已审核，未收货',
            2 => '已审核，未入库',
            3 => '已入库',
            -1 => '审核不通过'
        ];

        $this->assign([
            'statusList' => $statusList
        ]);
    }

    // 首页
    public function index(){
        $this->request->filter(['strip_tags','trim']);

        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            $total = $this->model
                ->with(['business'])
                ->where($where)
                ->order($sort,$order)
                ->count();

            $list = $this->model
                ->with(['business'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();

            $result = [
                'total' => $total,
                'rows' => $list
            ];

            return json($result);
            
        }

        return $this->view->fetch();
    }

    // 查看订单
    public function order(){
        if($this->request->isAjax()){
            $code = $this->request->param('code','','trim');

            // 查看订单是否存在
            $order = $this->OrderModel->where(['code'=>$code])->find();
            if(!$order){
                $this->error('订单不存在');
                exit;
            }

            $OrderProduct = $this->OrderProductModel->with(['products'])->where(['orderid'=>$order['id']])->select();

            $AddressList = $this->AddressModel->with(['provinces','citys','districts'])->where(['busid'=>$order['busid']])->select();

            $data = [
                'order' => $order,
                'OrderProduct' => $OrderProduct,
                'AddressList' => $AddressList
            ];

            $this->success('查询成功','',$data);

        }
    }


    // 添加退货
    public function add(){
        if($this->request->isPost()){
            $params = $this->request->param('row/a');

            // var_dump($params);
            // exit;
            // 开启事务
            $this->model->startTrans();
            $this->BackProductModel->startTrans();

            // 查询订单是否存在
            $order = $this->OrderModel->where(['code'=>$params['ordercode']])->find();

            if(!$order){
                $this->error('订单不存在');
                exit;
            }

            $OrderProduct = $this->OrderProductModel->where(['orderid'=>$order['id']])->select();
            if(!$OrderProduct){
                $this->error('订单商品不存在');
                exit;
            }
            // var_dump(collection($OrderProduct)->toArray());
            // exit;

            $address = $this->AddressModel->where(['id'=>$params['addrid']])->find();
            if(!$address){
                $this->error('请选择联系人及地址');
                exit;
            }

            // var_dump($address->toArray());
            // exit;

            // 封装退货单的数据
            $BackData = [
                'code' => build_code('BP'),
                'ordercode' => $params['ordercode'],
                'busid' => $order['busid'],
                'remark' => $params['remark'],
                'amount' => $order['amount'],
                'status' => 0,
                'adminid' => $this->auth->id,
                'contact' => $address['consignee'],
                'phone' => $address['mobile'],
                'address' => $address['address'],
                'province' => $address['province'],
                'city' => $address['city'],
                'district' => $address['district'],
            ];
            
            $BackStatus = $this->model->validate('common/Depot/Back')->save($BackData);
            if($BackStatus === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            // 封装退货商品数据
            $BackProductData = [];
            foreach($OrderProduct as $item){
                $BackProductData[] = [
                    'backid' => $this->model->id,
                    'proid' => $item['proid'],
                    'nums' => $item['pronum'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $BackProductStatus = $this->BackProductModel->validate('common/Depot/Productback')->saveAll($BackProductData);

            if($BackProductStatus === FALSE){
                $this->model->rollback();
                $this->error($this->BackProductModel->getError());
                exit;
            }

            if($BackStatus === FALSE || $BackProductStatus === FALSE){
                $this->BackProductModel->rollback();
                $this->model->rollback();
                $this->error('添加退货信息失败');
                exit;
            }else{
                $this->BackProductModel->commit();
                $this->model->commit();
                $this->success('添加退货信息成功');
                exit;
            }
        }
        return $this->view->fetch();
    }

    // 编辑退货
    public function edit($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $row = $this->model->with(['business'])->find($ids);

        if(!$row){
            $this->error('该退货信息不存在');
            exit;
        }

        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // 开启事务
            $this->model->startTrans();
            $this->BackProductModel->startTrans();

            // 查询订单是否存在
            $order = $this->OrderModel->where(['code'=>$params['ordercode']])->find();

            if(!$order){
                $this->error('订单不存在');
                exit;
            }

            $OrderProduct = $this->OrderProductModel->where(['orderid'=>$order['id']])->select();
            if(!$OrderProduct){
                $this->error('订单商品不存在');
                exit;
            }
            // var_dump(collection($OrderProduct)->toArray());
            // exit;

            $address = $this->AddressModel->where(['id'=>$params['addrid']])->find();
            if(!$address){
                $this->error('请选择联系人及地址');
                exit;
            }

            // var_dump($address->toArray());
            // exit;

            // 封装退货单的数据
            $BackData = [
                'id' => $ids,
                'ordercode' => $params['ordercode'],
                'busid' => $order['busid'],
                'remark' => $params['remark'],
                'amount' => $order['amount'],
                'status' => $row['status'],
                'adminid' => $this->auth->id,
                'contact' => $address['consignee'],
                'phone' => $address['mobile'],
                'address' => $address['address'],
                'province' => $address['province'],
                'city' => $address['city'],
                'district' => $address['district'],
            ];

            $BackStatus = $this->model->isUpdate(true)->save($BackData);
            if($BackStatus === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            // 定义退货商品状态为TRUE
            $BackProductStatus = TRUE;
            // 判断订单号是否有更新
            if($params['ordercode'] != $row['ordercode']){
                // 封装退货商品数据
                $BackProductData = [];
                foreach($OrderProduct as $item){
                    $BackProductData[] = [
                        'backid' => $this->model->id,
                        'proid' => $item['proid'],
                        'nums' => $item['pronum'],
                        'price' => $item['price'],
                        'total' => $item['total']
                    ];
                }

                $BackProductStatus = $this->BackProductModel->validate('common/Depot/Productback')->saveAll($BackProductData);
            }

            

            if($BackProductStatus === FALSE){
                $this->model->rollback();
                $this->error($this->BackProductModel->getError());
                exit;
            }

            if($BackStatus === FALSE || $BackProductStatus === FALSE){
                $this->BackProductModel->rollback();
                $this->model->rollback();
                $this->error('修改退货信息失败');
                exit;
            }else{
                $this->BackProductModel->commit();
                $this->model->commit();
                $this->success('修改退货信息成功');
                exit;
            }
        }

        // 查询地址数据
        $AddressWhere = [
            'consignee' => $row['contact'],
            'mobile' => $row['phone'],
            'address' => $row['address'],
            'province' => $row['province'],
            'city' => $row['city'],
            'district' => $row['district'],
            'busid' => $row['busid']
        ];

        $addrid = $this->AddressModel->where($AddressWhere)->value('id');

        $row['addrid'] = $addrid;

        $BackProductList = $this->BackProductModel->with(['product'])->where(['backid'=>$row['id']])->select();
        // var_dump(collection($BackProductList)->toArray());
        // exit;

        $AddressData = $this->AddressModel->with(['provinces','citys','districts'])->where(['busid'=>$row['busid']])->select();

        // 封装地址下拉列表
        $AddressList = [];
        foreach($AddressData as $key=>$item){
            $AddressList[$item['id']] = "联系人：{$item['consignee']} 联系方式：{$item['mobile']} 地址：{$item['provinces']['name']}-{$item['citys']['name']}-{$item['districts']['name']} {$item['address']}";
        }

        $this->assignconfig('back',['BackProductList' => $BackProductList]);

        $data = [
            'row' => $row,
            'AddressList' => $AddressList
        ];


        return $this->view->fetch('',$data);

    }

    // 删除(软删除)
    public function del($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $list = $this->model->where(['id' => ['IN',$ids]])->select();

        if(!$list){
            $this->error('该退货信息不存在');
            exit;
        }

        $result = $this->model->destroy($ids);

        if($result === FALSE){
            $this->error('删除失败');
            exit;
        }else{
            $this->success('删除成功');
            exit;
        }
    }

    // 回收站
    public function recyclebin(){
        $this->request->filter(['strip_tags','trim']);

        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            $total = $this->model
                ->onlyTrashed()
                ->with(['business'])
                ->where($where)
                ->order($sort,$order)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['business'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            

            $result = [
                'total' => $total,
                'rows' => $list
            ];

            return json($result);
        }
        return $this->view->fetch();
    }

    // 恢复
    public function restore($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $row = $this->model->onlyTrashed()->select($ids);

        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->onlyTrashed()->where(['id'=>$ids])->update(['deletetime'=>null]);

        if($result === FALSE){
            $this->error('恢复数据失败');
            exit;
        }else{
            $this->success('恢复数据成功');
            exit;
        }
    }

    // 销毁
    public function destroy($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $rows = $this->model->onlyTrashed()->select($ids);
        // var_dump(collection($rows)->toArray());
        // exit;

        if(!$rows){
            $this->error(__('No Results were found'));
            exit;
        }

        // 开启事务
        $this->model->startTrans();
        $this->BackProductModel->startTrans();

        // 删除
        $BackProductID = $this->BackProductModel->where(['backid'=>['IN',$ids]])->column('id');
        // var_dump($DepotProductID);
        // exit;

        $BackStutus = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->delete(true);

        if($BackStutus === FALSE){
            $this->error($this->model->getError());
            exit;
        }

        $BackProductStatus = $this->BackProductModel->where(['id'=>['IN',$BackProductID]])->delete(true);

        if($BackProductStatus === FALSE){
            $this->model->rollback();
            $this->error($this->BackProductModel->getError());
            exit;
        }
        foreach($rows as $item){
            if(!empty($item['thumbs'])){
                $thumbs = explode(',',$item['thumbs']);

                foreach($thumbs as $val){
                    @is_file('.'.$val) && @unlink('.'.$val);
                }
            }
        }

        if($BackStutus === FALSE || $BackProductStatus === FALSE){
            $this->BackProductModel->rollback();
            $this->model->rollback();
            $this->error('销毁失败');
            exit;
        }else{
            $this->BackProductModel->commit();
            $this->model->commit();
            $this->success('销毁成功');
            exit;
        }

    }

    // 退货详情
    public function info($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $row = $this->model->with(['business','express'])->find($ids);

        if(!$row){
            $this->error('该退货信息不存在');
            exit;
        }
        $BackProductList = $this->BackProductModel->with(['product'])->where(['backid' => $ids])->select();

        // var_dump(collection($BackProductList)->toArray());
        // exit;
        $this->assign([
            'row' => $row,
            'BackProductList' => $BackProductList
        ]);

    
        return $this->view->fetch();
    }

    // 审核通过
    public function process(){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');
            $row = $this->model->find($ids);

            if(!$row){
                $this->error('该退货信息不存在');
                exit;
            }

            $data = [
                'id' => $ids,
                'status' => 1,
                'reviewerid' => $this->auth->id
            ];

            $BackStatus = $this->model->isUpdate(true)->save($data);

            if($BackStatus === FALSE){
                $this->error('审核失败');
                exit;
            }else{
                $this->success('退货状态更新成功');
                exit;
            }
        }
    }

    // 审核不通过
    public function fail(){
        
        $ids = $this->request->param('ids',0,'trim');
        $row = $this->model->find($ids);

        if(!$row){
            $this->error('该退货信息不存在');
            exit;
        }

        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            if(empty($params['reason'])){
                $this->error('请填写不通过申请的原因');
                exit;
            }
            $data = [
                'id' => $ids,
                'status' => '-1',
                'reviewerid' => $this->auth->id,
                'reason' => $params['reason']
            ];

            $BackStatus = $this->model->isUpdate(true)->save($data);

            if($BackStatus === FALSE){
                $this->error('审核失败');
                exit;
            }else{
                $this->success('退货状态更新成功');
                exit;
            }
        }
        return $this->view->fetch();
    }

    // 撤销审核
    public function cancel($ids=NULL){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');
            $row = $this->model->find($ids);

            if(!$row){
                $this->error('该退货信息不存在');
                exit;
            }

            $data = [
                'id' => $ids,
                'status' => 0,
                'reviewerid' => $this->auth->id
            ];

            $BackStatus = $this->model->isUpdate(true)->save($data);

            if($BackStatus === FALSE){
                $this->error('审核失败');
                exit;
            }else{
                $this->success('退货状态更新成功');
                exit;
            }
        }
    }

    // 确认收货
    public function receipt(){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');
            $row = $this->model->find($ids);

            if(!$row){
                $this->error('该退货信息不存在');
                exit;
            }

            // 查询订单
            $order = $this->OrderModel->where(['code' => $row['ordercode']])->find();

            if(!$order){
                $this->error('订单信息不存在');
                exit;
            }

            // 查询客户
            $business = $this->BusinessModel->find($order['busid']);

            if(!$business){
                $this->error('客户不存在');
                exit;
            }

            // 开启事务
            $this->model->startTrans();
            $this->OrderModel->startTrans();
            $this->BusinessModel->startTrans();

            // 封装退货单的数据
            $BackData = [
                'id' => $ids,
                'status' => 2
            ];

            $BackStatus = $this->model->isUpdate(true)->save($BackData);

            if($BackStatus === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            // 更新用户余额
            $BusinessData = [
                'id' => $business['id'],
                'money' => bcadd($order['amount'],$business['money'],2)
            ];

            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

            if($BusinessStatus === FALSE){
                $this->model->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            $OrderData = [
                'id' => $order['id'],
                'status' => -4
            ];

            $OrderStatus = $this->OrderModel->isUpdate(true)->save($OrderData);

            if($OrderStatus === FALSE){
                $this->BusinessModel->rollback();
                $this->model->rollback();
                $this->error($this->OrderModel->getError());
                exit;
            }

            if($BackStatus === FALSE || $BusinessStatus === FALSE || $OrderStatus === FALSE){
                $this->OrderModel->rollback();
                $this->BusinessModel->rollback();
                $this->model->rollback();
                $this->error('确认收货失败');
                exit;
            }else{
                $this->OrderModel->commit();
                $this->BusinessModel->commit();
                $this->model->commit();
                $this->success('确认收货成功');
                exit;
            }
        }
    }

    // 确认入库
    public function storage(){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');
            $row = $this->model->find($ids);

            if(!$row){
                $this->error('该退货信息不存在');
                exit;
            }

            $BackProductList = $this->BackProductModel->where(['backid' => $ids])->select();

            if(!$BackProductList){
                $this->error('退货商品信息不存在');
                exit;
            }

            $this->model->startTrans();
            $this->StorageModel->startTrans();
            $this->StorageProductModel->startTrans();
            
            // 封装入库数据
            $StorageData = [
                'code' => build_code('SH'),
                'type' => 2,
                'amount' => $row['amount'],
                'status' => 0
            ];

            $StorageStatus = $this->StorageModel->validate('common/Depot/Storage.back')->save($StorageData);

            if($StorageStatus === FALSE){
                $this->error($this->StorageModel->getError());
                exit;
            }

            // 存放入库商品信息
            $StorageProductData = [];

            foreach($BackProductList as $item){
                $StorageProductData[] = [
                    'storageid' => $this->StorageModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $StorageProductStatus = $this->StorageProductModel->validate('common/Depot/Productstorage')->saveAll($StorageProductData);

            if($StorageProductStatus === FALSE){
                $this->StorageModel->rollback();
                $this->error($this->StorageProductStatus->getError());
                exit;
            }

            $BackData = [
                'id' => $row['id'],
                'status' => 3,
                'stromanid' => $this->auth->id,
                'storageid' => $this->StorageModel->id
            ];

            $BackStatus = $this->model->isUpdate(true)->save($BackData);

            if($BackStatus === FALSE){
                $this->BackProductModel->rollback();
                $this->StorageModel->rollback();
                $this->error($this->model->getError());
                exit;
            }

            if($StorageStatus === FALSE || $StorageProductStatus === FALSE || $BackStatus === FALSE){
                $this->model->rollback();
                $this->StorageProductModel->rollback();
                $this->StorageModel->rollback();
                $this->error('确认入库失败');
                exit;
            }else{
                $this->model->commit();
                $this->StorageProductModel->commit();
                $this->StorageModel->commit();
                $this->success('确认入库成功');
                exit;
            }


        }
    } 

}
